//app.js
import URL from './baseurl'
import pub from './pub.js'
import axios from 'axios'
import Qs from 'qs'
	var n = 0;
var config = {
	onLaunch: function() {
		let self = this;
		// 利用是否缓存sessionId 判断是否登录
		if (!uni.getStorageSync('sessionId')) { // 缓存sessionId为空
			uni.navigateTo({
				url: '/pages/main/login/login',
			})
		} else { // 缓存sessionId存在
			self.header['wxa-sessionid'] = uni.getStorageSync('sessionId');
			uni.request({
				url: URL + '/app/base/getLoginInfo',
				header: self.header,
				success(res) {
					if (res.data.code === '0') {
						self.globalData.userInfo = res.data.wxUser;
						if (res.data.user) {
							self.globalData.userInfo.mobile = res.data.user.mobile;
							self.globalData.user = res.data.user;
						} else {
							self.goLogin()
						}
						uni.$emit('userInfo', 'ok')
					} else if (res.data.code === '-200') {
						self.goLogin()
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
					// //console.log(self.globalData.userInfo, '用户信息')
				}
			})
		}
		// 展示本地存储能力
		var logs = uni.getStorageSync('logs') || []
		logs.unshift(Date.now())
		uni.setStorageSync('logs', logs)
	},
	// goLogin() {
	// 	uni.navigateTo({
	// 		url: '/pages/main/login/login',
	// 	})
	// },
	globalData: {
		userInfo: {},
		user: {},
		location: {},
		address: [],
		community: {},
	},
	header: {
		// 'content-Type': 'application/json',
		'content-type': 'application/x-www-form-urlencoded',
		'authorization': uni.getStorageSync('token') || uni.getStorage({
			key: "uerInfo",
			success(e) {
				return e.data
			}
		}) || '',
	},
	URL: URL,
	pub: pub,
	// 以下为异步请求相关
	toUrl: (obj) => {
		let str = '';
		for (let i in obj) {
			str += '&' + i + '=' + obj[i] || '';
		}
		str = str.substr(1);
		return str;
	},
	get: (url, obj) => {
		// return axios.get(URL + url + '?' + config.toUrl(obj));
		// #ifdef APP-PLUS
		// //console.log('5+App平台');
		return new Promise((resolve, reject) => {
			uni.request({
				url: URL + url + '?' + config.toUrl(obj),
				method: 'GET',
				header: config.header,
				data: config.toUrl(obj),
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err)
				},
				complete: () => {}
			});
		})
		// #endif
		// #ifdef H5
		// //console.log('H5平台');
		return axios({
			url: URL + url + '?' + config.toUrl(obj),
			method: 'GET',
			data: Qs.stringify(obj),
			data: config.toUrl(obj),
			withCredentials: false,
			xhrFields: {
				withCredentials: true
			},
			headers: config.header,
		});
		// #endif
	},
	post: (url, obj) => {
		// return axios.post(URL + url + '?' + config.toUrl(obj));
		// #ifdef APP-PLUS
		// //console.log('5+App平台');
		return new Promise((resolve, reject) => {
			uni.request({
				url: URL + url,
				method: 'POST',
				header: config.header,
				data: obj,
				withCredentials: false,
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err)
				},
				complete: () => {}
			});
		})
		// #endif

		// #ifdef H5
		return axios({
			url: URL + url,
			method: 'POST',
			data: Qs.stringify(obj),
			// data: obj,
			withCredentials: false,
			headers: config.header,
		});
		// #endif
	},
	// 处理错误信息
	handleError: (data) => {
		uni.$emit('loginOutCode',{data})
		//console.log(data, '看看')
		if (data.code === "-202") {
			return data.msg;
		} else if (data.code == '-201' && n==0) { //弹出异地登陆
			n++;
			uni.removeStorage({
				key: 'uerInfo'
			});
			uni.removeStorage({
				key: 'community'
			});
			uni.removeStorage({
				key: 'token'
			});
			uni.removeStorage({
				key: 'user'
			});
			uni.setStorageSync("loginstate",false)
			uni.showModal({
				title: '登录信息异常',
				content: data.msg,
				success: function(res) {
					uni.hideToast();
					if (res.confirm) {
						n=0;
						uni.redirectTo({
							url: '/pages/login/login2',
						})	
						
					} else if (res.cancel) {
						n=0;
						uni.redirectTo({
							url: '/pages/login/login2',
						})
					}
				}
			});
			
			return data.msg
			// 利用缓存重新登录
			// this.storageLogin();
		} else if (data.code == '-200') {
			return data.msg;
		} else {
			return data.msg	||'网络开了个小差～～';
		}
	},
	// 文件上传-阿里云OSS方法
	uploadOss(fileUrl, callback, progress) {
		config.post('/common/upload/getUploadPolicyAndSign', {}).then(resu => {
			let info = resu.data;
			let suffix = fileUrl.substr(fileUrl.indexOf(".")); // 获取文件后缀名
			let imgName = info.dir + (new Date().getTime()) + suffix;
			let uploadTask = uni.uploadFile({
				url: info.host,
				filePath: fileUrl,
				name: 'file',
				formData: {
					'key': imgName, // 文件名
					'policy': info.policy,
					'OSSAccessKeyId': info.accessid,
					'signature': info.signature,
					'success_action_status': '200',
				},
				success: (res, op) => {
					let newFileUrl = info.host + '/' + imgName; // 最终文件路径
					if (callback) callback(newFileUrl);
				},
				fail: (err) => {
					//console.log(err)
					err.wxaddinfo = info.host;
				},
				complete: (complete) => {
					//console.log(complete)
				}
			})
			// uploadTask.onProgressUpdate(res=>{
			// 	// //console.log("上传进度" + res.progress);
			// 	if(progress) {progress(res.progress)}
			// })
		})
	},
	// 图片上传服务器-formData上传
	upload(file, back) {
		// 文件上传
		// #ifdef APP-PLUS
		// //console.log('5+App平台');
		uni.uploadFile({
			url: URL + '/common/upload',
			filePath: file.path,
			name: 'file',
			formData: {
				// file: file,
			},
			header: config.header,
			success: (res, op) => {
				// let newFileUrl = info.host+'/'+imgName;  // 最终文件路径
				//console.log(res, '看看离开你克里夫')
				let data = JSON.parse(res.data)
				if (data.code === 200) {
					if (back) back(data);
				} else {
					config.handleError(data)
				}
			},
			fail: (err) => {
				//console.log(err)
			},
			complete: (complete) => {
				//console.log(complete)
			}
		})
		// #endif
		// #ifdef H5
		let formData = new FormData()
		formData.append('file', file)
		// formData.append('fileType', fileType)
		//console.log(formData);
		axios({
			method: "POST",
			url: URL + '/common/upload',
			data: formData,
			withCredentials: false,
			headers: config.header,
		}).then(res => {
			//console.log(res.data)
			if (res.data.code === 200) {
				if (back) back(res.data);
			} else {
				config.handleError(res.data)
			}
		})
		// #endif
	},
	// websocket连接
	wsConnect() {
		uni.connectSocket({
			url: 'wss://chang2.xiao2yun.com/ws' + '?is_operator=0&mobile=' + config.globalData.userInfo
				.mobile,
			// url: 'ws://192.168.0.111:10001'+'?is_operator=0&mobile='+config.globalData.userInfo.mobile,
		});

		uni.onSocketOpen(function() {
			//console.log('WebSocket 已连接！');
			uni.$emit('wsOpen', 'ok')
		});

		uni.onSocketClose(function(res) {
			//console.log('WebSocket 已关闭！');
			uni.$emit('wsOpen', 'no')
		});
		
	},

	// 获取个人信息
	getLoginInfo() {
		//uni.showLoading({title: '加载中',mask: true});
		//setTimeout(s=>{uni.hideLoading()},5000)
		config.get('/appIndexMenu/getUserInfo', {}).then(res => {
			//uni.hideLoading();
			// console.log(res)
			if (res.data.code === 200) {
				// res.data.data.birthday
				config.globalData.user = res.data.data;
				uni.setStorageSync('user', res.data.data)  //保留登陆用户的状态
				config.globalData.user.age = pub.analyzeIDCard(res.data.data.idCard).age
				uni.$emit('user', true);
			} else {
				if(res.data.code=='-201'){
							self.config.handleError(res.data)
						}else{
							uni.showToast({
								title: self.config.handleError(res.data),
								icon: 'none'
							});
						}
			}
		})
	},
	// 获取社区详情
	getCommunity() {
		//uni.showLoading({title: '加载中',mask: true});
		//	setTimeout(s=>{uni.hideLoading()},5000)
		config.post('/communityInfo/getCommunityDetail', {}).then(res => {
			//uni.hideLoading();
			// console.log(res)
			if (res.data.code === 200) {
				config.globalData.community = res.data.data;
			} else {
				if(res.data.code=='-201'){
							self.config.handleError(res.data)
						}else{
							uni.showToast({
								title: self.config.handleError(res.data),
								icon: 'none'
							});
						}
			}
		})
	},
	finIp(){
		const testip = 'http://39.98.118.19:8090';   //测试8080
		const correct = 'http://47.94.154.233:8090';  //正式
		const local = 'http://192.168.1.18:8080';  //本地测试
		return correct
	},
	getage(identityCard) {
	        var len = (identityCard + "").length;
	        var strBirthday = "";
	        if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
	        {
	            strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
	        }
	        if (len == 15) {
	            var birthdayValue='';
	            birthdayValue = identityCard.charAt(6)+identityCard.charAt(7);
	            if(parseInt(birthdayValue)<10){
	                strBirthday = "20" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
	            }else{
	                strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
	            }
	
	        }
	        //时间字符串里，必须是“/”
	        var birthDate = new Date(strBirthday);
	        var nowDateTime = new Date();
	        var age = nowDateTime.getFullYear() - birthDate.getFullYear();
	        //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
	        if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
	            age--;
	        }
	        return age;
	    }
}

config.getLoginInfo()
config.getCommunity()
config.finIp()

export default config;
